<template>
  <div class="app-container">
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="prop.title" :visible="prop.open" width="500px" append-to-body :close-on-click-modal="false" :show-close="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey" label="权限字符">
          <!-- <span slot="label">
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            权限字符
          </span> -->
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.isStop">
            <el-radio
              v-for="item in isStopEnableStatus"
              :key="item.value"
              :label="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.roleMenuCheck" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.roleMenuCheck"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel({isSaveData:false})">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { treeselectAll as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";
import {isStopEnableStatus} from "@/utils/constants/common/constants.js"
import { add , getDetail,edit, checkRoleNameUnique, checkRoleKeyUnique } from "@/api/system/role";
export default {
  name: "RoleEdit",
  props:{
    prop:{
      type:Object,
      default:function () {
        return {
          open:false,
          title:'添加角色',
          editId:null,
        }
      }
    }
  },
  data() {
    var nameValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        checkRoleNameUnique({roleName:value,roleId:this.form.roleId}).then(res =>{
          let isUnique = res.data
          if (isUnique) {
            return callback()
          }else{
            return callback(new Error('角色名称不能重复'));
          }
        })
      }else{
         return callback(new Error('角色名称不能为空'));
      }
    };
    var keyValidator = (rule, value, callback) => {
      if(value!==null&&value.trim()!==""){
        checkRoleKeyUnique({roleKey:value,roleId:this.form.roleId}).then(res =>{
          let isUnique = res.data
          if (isUnique) {
            return callback()
          }else{
            return callback(new Error('角色权限字符串不能重复'));
          }
        })
      }else{
         return callback(new Error('角色权限字符串不能为空'));
      }
    };
    return {
      isEdit:false,
      menuExpand: true,
      menuNodeAll: false,
      menuOptions: [],// 菜单列表
      defaultProps: {
        children: "children",
        label: "label"
      },
      isStopEnableStatus:isStopEnableStatus,
      // 表单参数
      form: {
        roleId: null,
        roleName: null,
        roleKey: null,
        isStop: "0",
        roleMenuCheck: true,
        remark: null
      },
      // 表单校验
      rules: {
        roleName: [
          { required: true, validator:nameValidator, trigger: "blur" }
        ],
        roleKey: [
          { required: true, validator:keyValidator,trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getDetail(){
      getDetail({roleId:this.prop.editId}).then(res => {
        let data = res.data;
        let roleMenus = data.roleMenus
        if(roleMenus){
          let selectKeys = roleMenus.map(item =>item.menuId)
          selectKeys.forEach(item =>{
            this.$refs.menu.setChecked(item,true,false);
          })
        }
        data.roleMenuCheck = data.roleMenuCheck==='1'?true:false
        this.handleCheckedTreeExpand(true,'menu')
        this.form = data
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let formData = this.setFormData()
          if (this.isEdit) {
            edit(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel({isSaveData:true})
            });
          } else {
            add(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel({isSaveData:true})
            });
          }
        }
      });
    },
    setFormData(){
      let roleData = {...this.form}
      roleData.roleMenuCheck = roleData.roleMenuCheck === true?'1':'0'
      let formData = {role:roleData}
      let menuSelected = this.getMenuAllCheckedKeys()
      let roleId = this.isEdit?this.form.roleId:null
      if(menuSelected){
        //根据选中菜单设置角色菜单关联数据
        formData.roleMenus = menuSelected.map(item =>{
          return {menuId:item,roleId:roleId}
        });
      }
      return formData
    },
    cancel(saveParams) {
      this.$emit('close',saveParams)
    },
  },
  mounted() {
    this.getMenuTreeselect();
    if(this.prop.editId){
      this.isEdit = true
      this.getDetail()
    }
  }
};
</script>
<style scoped>

</style>
